package com.javatest.springbootfileupload.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-12-26 下午2:23
 */
@Slf4j
@RestController
public class FileUploadController {

    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd/");

    @PostMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request) {
        String realPath = request.getSession().getServletContext().getRealPath("/uploadFile");
        String date = formatter.format(LocalDate.now());
        File folder = new File(realPath + date);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            uploadFile.transferTo(new File(folder, newName));
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +
                    "/uploadFile/" + date + newName;
            return filePath;
        } catch (IOException e) {
            log.error("upload error!", e);
        }

        return "上传失败!";
    }

    @PostMapping("/uploads")
    public String uploads(MultipartFile[] uploadFiles, HttpServletRequest request) {
        List<String> results = new ArrayList<>();
        for (MultipartFile uploadFile : uploadFiles) {
            results.add(upload(uploadFile, request));
        }

        return Arrays.toString(results.toArray());
    }

}
